<template>
  <div class="postReplyList">

    <!-- 筛选表单 -->
    <el-form class="searchForm" label-width="70px">
      <el-form-item label="发布日期" style="width: 30%;">
        <el-date-picker
          v-model="searchForm.publishDate"
          type="daterange"
          size="mini"
          start-placeholder="请选择开始日期"
          end-placeholder="请选择结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label-width="0">
        <el-button-group class="button-group">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">筛选</el-button>
          <el-button type="primary" size="mini" icon="el-icon-refresh" @click="handleResetSearchForm">重置</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      :data="postReplyList"
      :header-cell-style="{'text-align': 'center','background': 'rgb(248 248 248)'}"
      :cell-style="{'text-align': 'center'}"
    >
      <el-table-column label="编号" prop="id" />
      <el-table-column label="用户" prop="userInfo.nickName" />
      <el-table-column label="帖子" prop="post.title" />
      <el-table-column label="内容">
        <template slot-scope="scope">
          <el-button type="primray" plain size="mini" @click="handlePostReplyDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="发布日期" prop="publishDate" />
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button-group class="button-group">
            <el-button type="warning" size="mini" :loading="isButtonLoading" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" :loading="isButtonLoading" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :total="total"
      :current-page="pageNum"
      :page-size="pageSize"
      :page-sizes="[10,15,20,25,30]"
      layout="total, sizes, prev, pager, next, jumper"
      style="text-align: right;margin-right: 10px;"
      @current-change="handleChange"
      @size-change="handleSizeChange"
    />

    <!-- 帖子回复详情对话框 -->
    <el-dialog
      class="postReplyDialog"
      title="回复内容"
      :visible.sync="isPostReplyInfoDialogVisible"
    >
      <div style="border:1px solid rgb(216, 216, 216);padding: 0 0 0 10px;">
        <span v-html="format(postReplyInfo.content)" />
      </div>
    </el-dialog>

    <!-- 新增/修改对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isDialogVisible"
      @close="getPostReplyVoList"
    >
      <el-form
        ref="form"
        label-width="70px"
        :rules="rules"
        :model="postReplyForm"
        hide-required-asterisk
      >
        <el-form-item label="用户" prop="userId">
          <el-input v-model="postReplyForm.nickName" type="text" disabled />
        </el-form-item>
        <el-form-item label="帖子" prop="postId">
          <el-input v-model="postReplyForm.postTitle" type="text" disabled />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <Editor
            v-model="postReplyForm.content"
            class="editor"
            api-key="no-api-key"
            :init="editInit"
          />
        </el-form-item>
        <el-form-item label="发布日期" prop="publishDate">
          <el-date-picker
            v-model="postReplyForm.publishDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-button style="width: 100%;" type="primary" :loading="isButtonLoading" @click="handleSubmit">确定</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getPostReplyVoList, updatePostReply, savePostReply, deletePostReply } from '@/api/postReply'
import { upload } from '@/api/upload'
import Editor from '@tinymce/tinymce-vue'

export default {
  name: 'PostList',
  components: {
    Editor
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      postReplyList: [],
      userInfoList: [],
      postList: [],
      total: undefined,
      pageNum: 1,
      pageSize: 10,
      searchForm: {
        publishDate: undefined
      },
      dialogTitle: undefined,
      isDialogVisible: false,
      dialogType: undefined,
      postReplyForm: {
        id: undefined,
        nickName: undefined,
        postTitle: undefined,
        postId: undefined,
        content: '',
        publishDate: undefined
      },
      rules: {
        status: [{
          message: '请输选择状态',
          required: true,
          trigger: 'blur'
        }],
        content: [{
          message: '请输入内容',
          required: true,
          trigger: 'blur'
        }],
        publishDate: [{
          message: '请选择日期',
          required: true,
          trigger: 'blur'
        }]
      },
      isButtonLoading: false,
      postReplyInfo: {},
      isPostReplyInfoDialogVisible: false,
      editInit: {
        language: 'zh_CN',
        statusbar: false,
        plugins: 'image',
        images_upload_handler: (blobInfo, success, failure) => {
          // 创建一个 FormData 对象
          var formData = new FormData()
          // 将要上传的图片文件添加到 FormData 中
          formData.append('file', blobInfo.blob())
          upload(formData).then(res => {
            this.postReplyForm.content += `<img src='${this.baseUrl + res.data.imageUrl}'/>`
            success('')
          }, err => {
            console.log(err)
            failure('')
          })
        }
      },
      postStatusList: []
    }
  },
  beforeMount() {
    this.getPostReplyVoList()
  },
  methods: {
    format(content) {
      var regexp = /<img src="/gi
      return content ? content.replace(regexp, `<img src="${this.baseUrl}`) : content
    },
    handleSearch() {
      this.pageNum = 1
      this.pageSize = 10
      this.getPostReplyVoList()
    },
    handlePostReplyDetail(row) {
      this.postReplyInfo = row
      this.isPostReplyInfoDialogVisible = true
    },
    handleDelete(row) {
      this.$confirm(`确定要删除编号为${row.id}的数据吗?`, '提示').then(() => {
        this.isButtonLoading = true
        deletePostReply([row.id]).then(() => {}, () => {}).finally(() => {
          this.isButtonLoading = false
          this.getPostReplyVoList()
        })
      }, () => {})
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          var regexp = new RegExp(`<img src="${this.baseUrl}`, 'gi')
          this.postReplyForm.content = this.postReplyForm.content.replace(regexp, `<img src="`)
          if (this.dialogType === 'edit') {
            this.isButtonLoading = true
            updatePostReply(this.postReplyForm).then(() => {}, () => {}).finally(() => {
              this.isButtonLoading = false
              this.isDialogVisible = false
              this.getPostReplyVoList()
            })
          } else {
            this.postReplyForm.publishDate = new Date()
            savePostReply(this.postReplyForm).then(() => {}, () => {}).finally(() => {
              this.isButtonLoading = false
              this.isDialogVisible = false
              this.getPostReplyVoList()
            })
          }
        } else {
          console.log('表单验证有误')
        }
      })
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '修改帖子'
      this.isDialogVisible = true
      this.postReplyForm = row
      this.postReplyForm.nickName = row.userInfo.nickName
      this.postReplyForm.postTitle = row.post.title
      this.postReplyForm.postId = row.post.id
      var regexp = /<img src="/gi
      this.postReplyForm.content = this.postReplyForm.content.replace(regexp, `<img src="${this.baseUrl}`)
    },
    handleResetSearchForm() {
      this.searchForm = {
        publishDate: undefined
      }
      this.getPostReplyVoList()
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.getPostReplyVoList()
    },
    handleChange(value) {
      this.pageNum = value
      this.getPostReplyVoList()
    },
    async getPostReplyVoList() {
      const searchParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searches: [
          {
            key: 'pr.publish_date',
            rule: 'scope',
            value: this.searchForm.publishDate
          }
        ]
      }
      const { data: postReplyData } = await getPostReplyVoList(searchParam)
      this.total = postReplyData.total
      this.postReplyList = postReplyData.list
    }
  }
}
</script>

<style lang="scss">
.postReplyList {
  .postReplyDialog {
    .el-dialog__body {
      span {
        img {
          width: 98%;
        }
      }
    }
  }
}
.tox:not([dir=rtl]) {
  z-index: 5000;
}
</style>

<style lang="scss" scoped>
.postReplyList {
  .searchForm {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .el-form-item {
      width: 20%;
      margin-left: 5px;
      .el-select {
        width: 100%;
      }
    }
    .button-group {
      margin-left: 10px;
      width: 100%;
      justify-content: left;
    }
  }
  .button-group {
    display: flex;
    justify-content: center;
    .el-button {
      margin-right: 10px;
    }
  }
  .editor {
    height: 400px;
  }
}
</style>
